package com.controller;


import com.Util.EasyOutUtil;
import com.alibaba.excel.EasyExcel;
import com.template.EasyReadTemplate;
import com.template.EasyWriterTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import sun.security.util.ECUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.filechooser.FileSystemView;
import javax.websocket.server.PathParam;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Controller
public class SysController {
    /*
    *  --controller--
    *   uploads 文件总栏
    *   upload  文件上传
    * ---var---
    * uploadDir 输出目录
    * filePaths 上传文件管理
    * uploadsdir上传文件目录
    * 操作流程 判断文件为空 -> 文件上传-> 文件流读取-> 文件流写入合并
    * */
    File overfile=null;
    @PostMapping("/uploads")
    public String uploads(HttpServletRequest request, MultipartFile[] file, Model model){
        synchronized (this){
            String uploadDir=null;
            String over=null;
            String uploadsdir=null;
            boolean flag = true;//用来判断文件
            String osName = System.getProperty("os.name");//得到系统环境
            /*
            文件判断空
            */
            for (MultipartFile multipartFile : file) {
                if ("".equals(multipartFile.getOriginalFilename())){
                    over="请检查格式或者不要空选";
                flag=false;
                }
            }
                if (flag){
                    /*确定目录->文件上传*/
                        uploadDir = request.getSession().getServletContext().getRealPath("/") + "upload/";//确定缓存目录
                    List<String> filePaths = new ArrayList<>();//文件合集
                    for (MultipartFile multipartFile : file) {
                        if (null != multipartFile) {
                            if (multipartFile.getOriginalFilename().contains(".xlsx") || multipartFile.getOriginalFilename().contains(".xls")) {
                                if (upload(uploadDir,fileSplit(uploadDir+multipartFile.getOriginalFilename()),multipartFile)) {
                                    /*解决部分浏览器自动上传全值*/
//                                    filePaths.add(uploadDir +   EasyOutUtil.fileNameSplit(multipartFile.getOriginalFilename()));
                                    filePaths.add(uploadDir +  fileSplit(uploadDir+multipartFile.getOriginalFilename()));
                                }
                            }
                        }
                        uploadsdir=uploadDir;
                    }
                    /*文件输出 确定输出目录 win改为桌面*/
                    if (osName.startsWith("Windows")) {
                        javax.swing.filechooser.FileSystemView fsv = javax.swing.filechooser.FileSystemView
                                .getFileSystemView();
//                        uploadDir =  fsv.getHomeDirectory()+"/";//改为桌面

                    } else {

                        over="无权限写入，请自行目录查看"+uploadDir;
                    }
                    String fileOver = uploadDir + "合并.xlsx";//确定输出名字
                    EasyOutUtil easyOutUtil = new EasyOutUtil();//如果是单线程可以使用懒人模式，如果是多线程使用建议使用new 牺牲内存执行完毕cg会回收,或者使用线程管理
                    easyOutUtil.setFileNames(filePaths).setOutFileName(fileOver).
                            setReadTemplate(new EasyReadTemplate()).setWriterTemplate(new EasyWriterTemplate()).outStart();
                    System.out.println("输出目录:" + fileOver);
                    File shuFile=new File(fileOver);
                    if (shuFile.exists()){
                        overfile=shuFile;
                        over=String.format("合并完成%n成功合并个%s文件，共%s行，%s文件合并失败，请手动处理",easyOutUtil.getFileSize(),easyOutUtil.getDataSize(),easyOutUtil.getErrorList());

                    }
                    /*文件删除*/
                    model.addAttribute("url","/download");
                }
                model.addAttribute("msg", over);

        return "succeed";

    }
    }

    public  boolean upload(String Dir,String name, MultipartFile file) {
        //设置路径
        File dir=new File(Dir);
        if (!dir.exists())
            dir.mkdir();
        //上传文件名
        //服务端保留的文件名字
        File serverfile=new File(Dir+name);
        try {
            file.transferTo(serverfile);
        } catch (IOException e) {
            System.out.println("文件流上传失败");
            e.printStackTrace();
        }

        if (serverfile.exists()){
            System.out.println("文件上传成功   :"+serverfile);
            return true;
        }
        return false;
    }

    public  void deleteFile(String over){
        //判断文件不为null或文件目录存在
        File file=new File(over);
        if (file == null || !file.exists()){
            System.out.println("文件删除失败,请检查文件路径是否正确");
            return;
        }
        try {
            System.out.println("正在删除文件"+file.getPath()+file.getName());
            Thread.sleep(2000);
            file.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static String fileSplit(String name){
        char[] chars = name.toCharArray();
        boolean FN=false;
        String a=null;
        for (int i = chars.length-1; i >0; i--) {
            if (!FN){
                if (chars[i]==92||chars[i]=='/'){
                        FN=true;
                    System.out.println(name.substring(i+1,chars.length));
                    a=name.substring(i+1,chars.length);

                }
            }
        }
       return a;
    }
    @ResponseBody
    //    文件下载功能
    @GetMapping("/download")
    public     void downexcel(HttpServletResponse res) throws UnsupportedEncodingException, InterruptedException {
        Thread.sleep(1000);
        String fileName = "合并.xlsx";

        fileName = URLEncoder.encode(fileName, "utf-8");

        res.setHeader("content-type", "application/octet-stream");
        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename="+fileName);

        if (overfile.exists()){


//            获得url
        try {
            File file1=overfile;
            InputStream is = new FileInputStream(file1);
            byte[] buff = new byte[1024];
            int len;
            OutputStream os = res.getOutputStream();
            while ((len = is.read(buff)) != -1) {
                os.write(buff, 0, len);
            }
            os.flush();
            os.close();
            is.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        }

    }
}
